package work.hashmap;

import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.stream.Collectors;


public class Problem169 {
    public int majorityElement(int[] nums) {


        HashMap<Integer, Integer> map = creatMap(nums);
        Map.Entry<Integer, Integer> singleMap = null;
        for (Map.Entry<Integer, Integer> newMap : map.entrySet()) {
            if (singleMap == null || newMap.getValue() > singleMap.getValue()) {
                singleMap = newMap;
            }
        }
        return singleMap.getKey();
    }

    private HashMap<Integer, Integer> creatMap(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }
        return map;
    }

    public static void main(String[] args) {
        Problem169 problem169 = new Problem169();

    }

    public int majorityElement11(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            Integer orDefault = map.getOrDefault(num, 0);
            orDefault++;
            map.put(num, orDefault);
        }
        for (int key : map.keySet()) {
            if (map.get(key) > nums.length / 2) return key;
        }
        return 0;
    }


    public int majorityElement12(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        return nums[n/2];
    }
}
